/*
 * NewConnectionDialog.java
 *
 * Created on Štvrtok, 2008, marec 13, 17:44
 */
package feedback;

import XML.XmlConnections;
import db.ConnectionProperties;
import db.execute.Connect;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author  abracadabuda
 */
public class NewConnectionDialog extends javax.swing.JDialog {

    private ArrayList<ConnectionProperties> conProps;
    private XmlConnections xmlCons;
    private Vector<String> listOfSavedCons;
    private boolean canConnect = false;

    /** Creates new form NewConnectionDialog */
    public NewConnectionDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        loadSavedConnections();
    }

    private void loadSavedConnections() {
        xmlCons = new XmlConnections();
        conProps = xmlCons.loadConnections();
        listOfSavedCons = new Vector<String>();
        for (ConnectionProperties conProp : conProps) {
            listOfSavedCons.add(conProp.getName());
        }
        savedConnectionsList.setListData(listOfSavedCons);
    }

    private ConnectionProperties getConPropFromList() {
        int poz = savedConnectionsList.getSelectedIndex();
        return conProps.get(poz);
    }

    public String getUsername() {
        return usernameTextField.getText().trim();
    }

    public String getPassword() {
        return passwordTextField.getText().trim();
    }

    public String getDatabaseName() {
        return databaseTextField.getText().trim();
    }

    public String getHost() {
        return hostTextField.getText().trim();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        usernameTextField = new javax.swing.JTextField();
        passwordTextField = new javax.swing.JTextField();
        databaseTextField = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        connectButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        savedConnectionsList = new javax.swing.JList();
        saveButton = new javax.swing.JButton();
        loadButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        hostTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(feedback.FeedBackApp.class).getContext().getResourceMap(NewConnectionDialog.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        usernameTextField.setText(resourceMap.getString("usernameTextField.text")); // NOI18N
        usernameTextField.setName("usernameTextField"); // NOI18N

        passwordTextField.setText(resourceMap.getString("passwordTextField.text")); // NOI18N
        passwordTextField.setName("passwordTextField"); // NOI18N

        databaseTextField.setText(resourceMap.getString("databaseTextField.text")); // NOI18N
        databaseTextField.setName("databaseTextField"); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        connectButton.setText(resourceMap.getString("connectButton.text")); // NOI18N
        connectButton.setName("connectButton"); // NOI18N
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        savedConnectionsList.setName("savedConnectionsList"); // NOI18N
        savedConnectionsList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                savedConnectionsListMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(savedConnectionsList);

        saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
        saveButton.setName("saveButton"); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        loadButton.setText(resourceMap.getString("loadButton.text")); // NOI18N
        loadButton.setName("loadButton"); // NOI18N
        loadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadButtonActionPerformed(evt);
            }
        });

        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setName("deleteButton"); // NOI18N
        deleteButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteButtonActionPerformed(evt);
            }
        });

        hostTextField.setText(resourceMap.getString("hostTextField.text")); // NOI18N
        hostTextField.setName("hostTextField"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(deleteButton)
                            .addComponent(loadButton)
                            .addComponent(saveButton)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(databaseTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(connectButton))
                            .addComponent(hostTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(122, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {databaseTextField, hostTextField, passwordTextField, usernameTextField});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {deleteButton, loadButton, saveButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hostTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(passwordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(connectButton)
                            .addComponent(databaseTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(jLabel3)))
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(loadButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(deleteButton)))
                .addContainerGap(76, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        try {
            Connect testConnect = new Connect(hostTextField.getText().trim(),usernameTextField.getText().trim(), passwordTextField.getText().trim(), databaseTextField.getText().trim());
            canConnect = true;
            this.setVisible(false);
        } catch (SQLException ex) {
            Logger.getLogger(NewConnectionDialog.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(null, ex.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
            canConnect = false;
        } catch (ClassNotFoundException ex) {//GEN-LAST:event_connectButtonActionPerformed
            Logger.getLogger(NewConnectionDialog.class.getName()).log(Level.SEVERE, null, ex);
            canConnect = false;
        }
    }                                             

    /**
     * loads connection into fields
     * @param evt
     */
    private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
        ConnectionProperties conProp = getConPropFromList();
        usernameTextField.setText(conProp.getUsername());
        passwordTextField.setText(conProp.getPassword());
        databaseTextField.setText(conProp.getDatabaseName());
        hostTextField.setText(conProp.getHost());
    }//GEN-LAST:event_loadButtonActionPerformed

    /**
     * deletes connection 
     * @param evt
     */
    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
        ConnectionProperties conPropForDel = getConPropFromList();
        xmlCons.deleteConnection(conPropForDel.getName());
        conProps = xmlCons.loadConnections();
        listOfSavedCons = new Vector<String>();
        for (ConnectionProperties conProp : conProps) {
            listOfSavedCons.add(conProp.getName());
        }
        savedConnectionsList.setListData(listOfSavedCons);
        savedConnectionsList.updateUI();
    }//GEN-LAST:event_deleteButtonActionPerformed

    private void savedConnectionsListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_savedConnectionsListMouseClicked
        //if click count == 2, loads the selected connection
        if(evt.getClickCount() == 2) {
            getConPropFromList();
            loadButtonActionPerformed(null);
        }
        //if click count == 3, opens the selected connection
        if(evt.getClickCount() == 3) {
            connectButtonActionPerformed(null);
        }
    }//GEN-LAST:event_savedConnectionsListMouseClicked

    /**
     * opens up a windows, gets the name of the config and call save
     * @param evt
     */
    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            String name = JOptionPane.showInputDialog("Name for current config:");
            if (isGoodName(name)) {
                xmlCons.saveConnection(hostTextField.getText().trim(), databaseTextField.getText().trim(), usernameTextField.getText().trim(), passwordTextField.getText().trim(), name);
                conProps = xmlCons.loadConnections();
                listOfSavedCons = new Vector<String>();
                for (ConnectionProperties conProp : conProps) {
                    listOfSavedCons.add(conProp.getName());
                }
                savedConnectionsList.setListData(listOfSavedCons);
                savedConnectionsList.updateUI();
            }
        } catch (IOException ex) {
            Logger.getLogger(NewConnectionDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * returns true if name is not blank or it alrady used
     * @param name
     * @return
     */
    private boolean isGoodName(String name) {
        if (name.equals("")) {
            return false;
        }
        for (String savedCon : listOfSavedCons) {
            if (name.equals(savedCon.toString())) {
                return false;
            }
        }
        return true;
    }

    /**
     * check the text fields on form
     * @return true, if all fields are filled
     */
    public boolean isLoaded() {
        return canConnect && !(usernameTextField.getText().trim().equals("") ||
                passwordTextField.getText().trim().equals("") ||
                databaseTextField.getText().trim().equals("") ||
                hostTextField.getText().trim().equals(""));
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton connectButton;
    private javax.swing.JTextField databaseTextField;
    private javax.swing.JButton deleteButton;
    private javax.swing.JTextField hostTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton loadButton;
    private javax.swing.JTextField passwordTextField;
    private javax.swing.JButton saveButton;
    private javax.swing.JList savedConnectionsList;
    private javax.swing.JTextField usernameTextField;
    // End of variables declaration//GEN-END:variables
}
